package com.jg.comm.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;


@Component
public class FileUploadUtil {
    @Value("${file.upload-path}")
    private String BASE_UPLOAD_DIR;


    /**
     * 上传文件，返回相对路径
     */
    /**
     * 上传图片到 classpath:/static/uploads/images/
     */
    public String uploadImage(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 只允许图片
        String contentType = file.getContentType();
        System.out.println("图片类型：" + contentType);
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("仅支持图片文件上传");
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String uniqueFileName = UUID.randomUUID() + fileExtension;

        // 构建目标路径：classpath:/static/uploads/images/xxx.jpg
        Path destinationPath = Paths.get(BASE_UPLOAD_DIR + uniqueFileName);

        // 确保目录存在
        Files.createDirectories(destinationPath.getParent());

        // 保存文件
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, destinationPath, StandardCopyOption.REPLACE_EXISTING);
        }

        // 返回访问路径（前端可通过 /uploads/images/xxx.jpg 访问）
        return "/uploads/images/" + uniqueFileName;
    }

}
